package com.whacos.modules.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.enums.Constant;
import com.whacos.common.enums.DelFlagEnum;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.DateUtils;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.blog.entity.Content;
import com.whacos.modules.blog.service.ContentService;
import com.whacos.modules.blog.vo.ContentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongdun
 * @description 文章内容
 * @since 2018/11/17 17:11
 */
@Controller
@RequestMapping("/blog/content")
@Slf4j
public class ContentController extends BaseController {
    @Autowired
    private ContentService contentService;

    @GetMapping()
    @RequiresPermissions("blog:content:content")
    public String content() {
        return "blog/content/content";
    }

    // @Log("查询博客内容列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("blog:content:content")
    public IPage<ContentVO> list(ContentVO contentVO) {
        IPage<ContentVO> contentVOPage = new Page<>();
        try {
            // 请求参数
            Content content = new Content();
            BeanUtils.copyProperties(contentVO, content);
            // 查询数据
            IPage<Content> contentPage = contentService.page(new Page<>(contentVO.getPageNum(), contentVO.getPageSize()),
                    new LambdaQueryWrapper<Content>()
                            .eq(StringUtils.isNotEmpty(content.getType()), Content::getType, content.getType())
                            .eq(StringUtils.isNotEmpty(content.getTitle()), Content::getTitle, content.getTitle())
                            .eq(StringUtils.isNotEmpty(content.getCategories()), Content::getCategories, content.getCategories())
                            .eq(StringUtils.isNotEmpty(content.getAuthor()), Content::getAuthor, content.getAuthor())
                            .eq(ObjectUtils.isNotEmpty(content.getStatus()), Content::getStatus, content.getStatus())
                            .orderByDesc(Content::getUpdatedDate));
            // 返回结果
            BeanUtils.copyPage(contentPage, contentVOPage);
        } catch (Exception e) {
            log.error("查询博客内容列表异常，异常原因：" + e.getMessage(), e);
        }
        return contentVOPage;
    }

    // @Log("新增博客内容")
    @GetMapping("/add")
    @RequiresPermissions("blog:content:add")
    public String add() {
        return "blog/content/add";
    }

    // @Log("跳转到修改博客内容")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("blog:content:edit")
    public String edit(@PathVariable("id") Long id, Model model) {
        Content content = contentService.getById(id);
        model.addAttribute("content", content);
        return "blog/content/edit";
    }

    @Log("保存博客内容")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("blog:content:add")
    public ResponseVO save(ContentVO contentVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Content content = new Content();
            BeanUtils.copyProperties(contentVO, content);
            if (content.getAllowComment() == null) {
                content.setAllowComment(0);
            }
            if (content.getAllowFeed() == null) {
                content.setAllowFeed(0);
            }
            if (null == content.getType()) {
                content.setType("article");
            }
            content.createdData(this.getUserId());
            content.setDelFlag(DelFlagEnum.NORMAL.getValue());
            this.contentService.save(content);
            return ResponseVO.success().put("id", content.getId());
        } catch (Exception e) {
            return ResponseVO.error();
        }
    }

    @Log("修改博客内容")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("blog:content:edit")
    public ResponseVO update(ContentVO contentVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Content content = new Content();
            BeanUtils.copyProperties(contentVO, content);
            content.updatedData(this.getUserId());
            if (contentService.updateById(content)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("删除博客内容")
    @ResponseBody
    @PostMapping("/remove")
    @RequiresPermissions("blog:content:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Content content = new Content();
            content.setId(id);
            content.updatedData(this.getUserId());
            content.setDelFlag(DelFlagEnum.DELETE.getValue());
            if (contentService.updateById(content)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("批量删除博客内容")
    @ResponseBody
    @PostMapping("/batchRemove")
    @RequiresPermissions("blog:content:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            List<Content> contentList = new ArrayList<>();
            ids.forEach(id -> {
                Content content = new Content();
                content.setId(id);
                content.updatedData(this.getUserId());
                content.setDelFlag(DelFlagEnum.DELETE.getValue());
                contentList.add(content);
            });
            if (contentService.updateBatchById(contentList)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }
}
